package com.ky.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.hutool.core.util.RandomUtil;

import com.ky.common.config.RedisKeyConfig;
import com.ky.common.param.OrderAdd;
import com.ky.common.vo.R;
import com.ky.user.entity.Orders;
import com.ky.course.mapper.OrdersMapper;
import com.ky.course.service.OrdersService;
import com.ky.user.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author zpa
 * @since 2024-06-20
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public R findAllOrders() {
        List<Orders> orders = ordersMapper.selectList(null);
        return R.ok(orders);
    }


    @Override
    public R createOrder(String token, OrderAdd orderAdd) {
        User user = (User) redisTemplate.opsForValue().get(RedisKeyConfig.LOGIN_TOKEN + token);
        // 获取用户的id
        if(user==null ){
            return R.fail("用户未登录");
        }

        Integer id = user.getId();
        if (id == null){
            return R.fail("用户id为空");
        }
        String no = "v" + System.currentTimeMillis()+ RandomUtil.randomNumbers(6);

        Orders orders = new Orders();
        orders.setCourseId(orderAdd.getCourseId())
                .setUserId(id)
                .setAddressId(orderAdd.getAddressId())
                .setTotalAmount(orderAdd.getTotalAmount())
                .setStatus(1)
                .setOrderTime(new Date())
                .setNo(no);
        return ordersMapper.insert(orders)>0?R.ok():R.fail("失败");
    }

    @Override
    public R findAllOrderByType(Integer status) {
        if (status == 0){
            List<Orders> order = ordersMapper.selectList(null);
            return R.ok(order);
        }else {
            QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status",status);
            List<Orders> questions = ordersMapper.selectList(queryWrapper);
            return R.ok(questions);
        }
    }

}
